import sys
sys.path.append("..")   #也可以这样
from config import kMongdbUri
from datetime import datetime, timedelta
from datetime import datetime, timedelta
from pymongo import UpdateOne
from loguru import logger
import random
def get_date_string():
    from datetime import date
    today = date.today()
    date_string = today.strftime("%Y-%m-%d")
    return date_string


def read_file_data(file_path, num):
    with open(file_path) as fl:
        titles = [title.strip() for title in fl.readlines() if title]
        num = min(num, len(titles))  # 确保抽取的数量不超过标题的长度
        return random.sample(titles, num)  # 随机抽取标题

def group_list(lst, group_len):
    return [lst[i:i + group_len] for i in range(0, len(lst), group_len)]

def determine_video_orientation(width, height):
    """
    # 获取视频是横版还是竖版的方式
    """
    # 横版
    if width > height:
        return 2
    else:
        # 竖版
        return 1

def get_date_x_days_ago(x_days=0):
    """
    Returns the date that is x days before today as a string in the format 'YYYY-MM-DD'.

    :param x_days: The number of days before today.
    :return: A string representing the date x days ago.
    """
    target_date = datetime.now() - timedelta(days=x_days)
    return target_date.strftime("%Y-%m-%d")


def get_datetime_x_days_ago(x_days):
    """
    Returns the datetime that is x days before the current time as a string in the format 'YYYYMMDD_HHMMSS'.

    :param x_days: The number of days before today.
    :return: A string representing the datetime x days ago.
    """
    target_datetime = datetime.now() - timedelta(days=x_days)
    return target_datetime.strftime("%Y%m%d_%H%M%S")


class Mymongo:
    def __init__(self):
        import pymongo
        self.conn = pymongo.MongoClient(kMongdbUri)  # 这是mongos  
        self.db = self.conn["快手投放系统"]  # 假定名为test的db已经存在  

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.conn.close()
        
    def delete_and_insert(self, collection_name, list_data,advertiser_id):
        collection = self.db[collection_name]
        collection.delete_many({'advertiser_id': advertiser_id})  # 根据广告主id来删除他对应的素材
        collection.insert_many(list_data)


    def fetch_and_update(self, collection_name,advertiser_id, max_video_count, num_samples, increment_value=1):
        # video_data = mongo.fetch_and_update("可用素材列表",advertiser_id=str(adv_id),max_video_count=max_video_count,num_samples=num)
        collection = self.db[collection_name]

        pipeline = [
            {'$match': {'video_count': {'$lte': max_video_count}, 
                        'advertiser_id': advertiser_id,
                        'video_cover_id': {'$exists': True}}},
            {'$sample': {'size': num_samples}}
        ]
        samples = list(collection.aggregate(pipeline))

        # Prepare bulk update operations
        update_ops = [
            UpdateOne(
                {'_id': sample['_id']},
                {'$inc': {'video_count': increment_value}}
            ) for sample in samples
        ]

        # Perform bulk update
        if update_ops:
            collection.bulk_write(update_ops)

        return samples

    def rollback_update(self, collection_name, document_ids, decrement_value=1):
        collection = self.db[collection_name]

        # Prepare bulk update operations
        update_ops = [
            UpdateOne(
                {'_id': doc_id},
                {'$inc': {'video_count': -decrement_value}}
            ) for doc_id in document_ids
        ]

        # Perform bulk update
        if update_ops:
            collection.bulk_write(update_ops)
    
    # 获取模板的计划
    def get_template_plan(self,collection_name,qeury_dict):
        collection = self.db[collection_name]
        return collection.find_one(qeury_dict)